package com.wsl.controller;

import com.wsl.Entity.People;
import com.wsl.Entity.Peoples;
import com.wsl.utils.XmlUtil;
import net.sf.saxon.Configuration;
import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.s9api.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author:WangShuliang
 * @Description:
 * @Date:Created in 15:29 2018/3/15
 * @Modified by:
 */
@RestController
public class BeanToXmlController {
    private static TransformerFactory transformerFactory = null;
    private static Processor proc;
    private static HashMap<String, XsltExecutable> xslCache = new HashMap();
    private static final Log logger = LogFactory.getLog(BeanToXmlController.class);

    @RequestMapping("get/beanToXml")
    public String beanToXml() {
        People peoplewsl = new People();
        peoplewsl.setAge("25");
        peoplewsl.setName("王书亮");
        peoplewsl.setSex("1");
        peoplewsl.setScore("99");
        People people = new People();
        people.setAge("24");
        people.setName("张三");
        people.setSex("0");
        people.setScore("76");
        List<People> list = new ArrayList<People>();
        list.add(people);
        list.add(peoplewsl);
        Peoples peoples = new Peoples();
        peoples.setPeopleList(list);
        String msg = XmlUtil.getString(peoples);
        System.out.println("bean转换成普通的报文"+msg);
        String xslPath = "xsl/for.xsl";
        // resource =
        //加载资源
        Resource resource = new ClassPathResource(xslPath);
        logger.info(resource.toString());
        // 非标准报文转换成标准的报文
        String result = xslTransform(msg, resource);
        return result;
    }

    @RequestMapping("list")
    public void get() {
        int i = 100;
        ArrayList<Object> list = new ArrayList<Object>();
        list.add(new Object());
        change(i, list);
        System.out.println(""+i+"    "+list.size());
    }

    private static void change(int i, ArrayList<Object> list) {
        i = 0;
        list.clear();
    }

    /**
     * 新的转化引擎
     *
     * @param strXml
     * @param xslFile
     * @return
     */
    public String xslTransform(String strXml, Resource xslFile) {
        Serializer out = null;
        StringWriter writer = new StringWriter(1024);
        XsltTransformer trans = null;
        StringReader xmlReader = null;
        try {//xslCache缓存
            XsltExecutable exp = xslCache.get(xslFile.getURL().getPath());
            System.out.println(xslFile.getURL().getPath());
            if (exp == null) {
                StreamSource xslStream = new StreamSource(xslFile.getInputStream());
                XsltCompiler comp = proc.newXsltCompiler();
                exp = comp.compile(xslStream);
                xslCache.put(xslFile.getURL().getPath(), exp);
            }
            xmlReader = new StringReader(strXml);
            StreamSource xmlStream = new StreamSource(xmlReader);
            if (logger.isDebugEnabled()) {
                logger.debug("解析xml:" + strXml);
            }
            out = proc.newSerializer();
            out.setOutputWriter(writer);
            trans = exp.load();
            trans.setSource(xmlStream);
            trans.setDestination(out);
            trans.transform();
            String result = writer.toString();
            return result;
        } catch (FileNotFoundException sae) {
            logger.warn("未找到转换模板，非互联网核心交易！" + sae.getMessage(), sae);
            try {
                xmlReader.close();
                out.close();
                writer.close();
                trans.close();
            } catch (Exception e) {
            }
        } catch (Exception sae) {
            logger.error("XML报文转化失败！" + sae.getMessage(), sae);
            try {
                xmlReader.close();
                out.close();
                writer.close();
                trans.close();
            } catch (Exception e) {
            }
        } finally {
            try {
                out.close();
                writer.close();
                trans.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    static {
        Configuration configuration = new Configuration();
        proc = new Processor(false);
        configuration.setProcessor(proc);
        transformerFactory = new TransformerFactoryImpl(configuration);
    }
}